import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:vibration/vibration.dart';
import 'package:markdown/markdown.dart' as markdown;
import 'package:html/parser.dart';

import '../common/images.dart';
import '../common/routes.dart';
import '../common/utils.dart';

import '../controllers/message_controller.dart';
import '../model/message_record_model.dart';
import '../widgets/empty_view.dart';
import '../widgets/error_view.dart';
import '../widgets/loading_view.dart';

class MessagePage extends StatelessWidget {
  const MessagePage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      init: MessageController(),
      builder: (controller) {
        return Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(backgroundColor: Colors.white, surfaceTintColor: Colors.white, title: const Text('消息')),
          body: Stack(
            children: <Widget>[
              RefreshIndicator(
                onRefresh: () async {
                  controller.refreshData();
                },
                child: Stack(
                  children: [
                    ListView.builder(
                      itemCount: controller.recordList.isNotEmpty ? controller.recordList.length : 1,
                      itemBuilder: (BuildContext context, int index) {
                        if (controller.recordList.isNotEmpty) {
                          var recordItem = controller.recordList[index];
                          return RecordListItem(recordItem: recordItem, deleteChat: controller.deleteChat);
                        } else {
                          return const SizedBox(
                            width: double.infinity,
                            height: 500,
                            child: EmptyView(),
                          );
                        }
                      },
                    ),
                  ],
                ),
              ),
              Offstage(
                  offstage: !controller.isShowError,
                  child: ErrorView(retryAction: () {
                    controller.refreshData();
                  })),
              Offstage(offstage: !controller.isLoading, child: const LoadingView()),
            ],
          ),
        );
      },
    );
  }
}

class RecordListItem extends StatelessWidget {
  final MessageRecordModel recordItem;
  final Function(String) deleteChat;

  const RecordListItem({super.key, required this.recordItem, required this.deleteChat});

  _buildPipeRecordListItem() {
    if (recordItem.pipeList.length == 1) {
      return RecordListItemView(pipeInfo: recordItem.pipeList.first, deleteChat: deleteChat);
    } else if (recordItem.pipeList.length == 2) {
      return Column(
        children: [RecordListItemView(pipeInfo: recordItem.pipeList.first, deleteChat: deleteChat), Divider(color: Colors.grey[100]), RecordListItemView(pipeInfo: recordItem.pipeList.last, deleteChat: deleteChat)],
      );
    } else {
      return Column(
        children: [
          RecordListItemView(pipeInfo: recordItem.pipeList.first, deleteChat: deleteChat),
          Divider(color: Colors.grey[100]),
          RecordListItemView(pipeInfo: recordItem.pipeList.last, deleteChat: deleteChat),
          GestureDetector(
            child: const Padding(
              padding: EdgeInsets.fromLTRB(30, 10, 30, 0),
              child: Text(
                "更多消息",
                style: TextStyle(color: Colors.grey, fontSize: 13),
              ),
            ),
            onTap: () {},
          )
        ],
      );
    }
  }

  _buildCartoonInfoView() {
    return InkWell(
      onTap: () {
        var cartoonId = recordItem.id ?? "";
        Get.toNamed(Routes.CARTOON_INFO, arguments: {"cartoonId": cartoonId});
      },
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(16),
            child: CachedNetworkImage(
              fit: BoxFit.cover,
              fadeInDuration: const Duration(milliseconds: 100),
              fadeOutDuration: const Duration(seconds: 0),
              imageUrl: recordItem.avatar ?? '',
              width: 32,
              height: 32,
            ),
          ),
          const SizedBox(width: 10),
          Text(
            recordItem.name ?? '',
            style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
          ),
          const SizedBox(width: 10),
          if (recordItem.badge.isNotEmpty && recordItem.badge.first.level > 0)
            Stack(
              clipBehavior: Clip.none,
              children: [
                Image.asset(
                  recordItem.badge.first.style == "0" ? "assets/images/icon_level_bg_green.png" : "assets/images/icon_level_bg_gray.png",
                  fit: BoxFit.cover,
                  width: 56,
                  height: 16,
                ),
                Positioned(
                  top: -5,
                  child: CachedNetworkImage(
                    fit: BoxFit.cover,
                    fadeInDuration: const Duration(milliseconds: 100),
                    fadeOutDuration: const Duration(seconds: 0),
                    imageUrl: recordItem.badge.first.icon,
                    width: 24,
                    height: 24,
                  ),
                ),
                Positioned(
                  left: 24,
                  top: -3,
                  child: Text(
                    "LV${recordItem.badge.first.level}",
                    style: TextStyle(color: recordItem.badge.first.style == "0" ? const Color(0xFF79E279) : const Color(0xFFD5A08A), fontFamily: "Sansita", fontSize: 13),
                  ),
                ),
              ],
            ),
          const Spacer(),
          const Icon(Icons.chevron_right, color: Colors.grey)
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(10, 8, 10, 8),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          boxShadow: const [
            BoxShadow(
              color: Color.fromRGBO(0, 0, 0, 0.06),
              blurRadius: 10,
              spreadRadius: 2,
            ),
          ],
          border: Border.all(
            color: const Color.fromRGBO(0, 0, 0, 0.1),
            width: 0.5,
          ),
        ),
        child: Padding(
          padding: const EdgeInsets.all(10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [_buildCartoonInfoView(), const SizedBox(height: 12), _buildPipeRecordListItem()],
          ),
        ), // Add child widget here
      ),
    );
  }
}

class RecordListItemView extends StatelessWidget {
  final PipeInfo pipeInfo;
  final Function(String) deleteChat;

  const RecordListItemView({super.key, required this.pipeInfo, required this.deleteChat});

  String _getLatestMsg() {
    var latest = pipeInfo.content.where((msg) {
      String type = msg.type ?? "";
      return msg.sub == null && type != "bg" && type != "sound" && type != "bgm" && type != "btn" && type != "role" && type != "level";
    }).toList();

    var lastMsg = latest.reversed.where((msg) => msg.type == "str" && msg.val.isNotEmpty).firstOrNull;
    if (lastMsg != null) {
      var strContent = lastMsg.val;
      if (strContent.isNotEmpty) {
        return strContent;
      }
    }

    var last = latest.lastWhere((msg) => msg.val.isNotEmpty);
    if (last.val.isEmpty) {
      return "";
    } else if (last.type == "video") {
      return "[视频]";
    } else if (last.type == "audio") {
      return "[音频]";
    } else if (last.type == "img") {
      return "[图片]";
    } else if (last.type == "str") {
      return last.val;
    } else {
      return "";
    }
  }

  void _showContextMenu(BuildContext context, Offset position) async {
    var hasVibrator = await Vibration.hasVibrator() ?? false;
    if (hasVibrator) {
      await Vibration.vibrate(duration: 50, amplitude: 50);
    }

    final result = await showMenu(
      color: Colors.white,
      elevation: 2,
      context: context,
      position: RelativeRect.fromLTRB(position.dx, position.dy, position.dx, position.dy),
      items: [
        PopupMenuItem(
          value: 'set_top',
          child: Row(
            children: [Image.asset(Images.set_top, width: 24, height: 24, fit: BoxFit.cover), const SizedBox(width: 5), const Text('置顶聊天')],
          ),
        ),
        PopupMenuItem(
          value: 'delete',
          child: Row(
            children: [Image.asset(Images.delete, width: 24, height: 24, fit: BoxFit.cover), const SizedBox(width: 5), const Text('删除')],
          ),
        ),
      ],
    );

    // Handle the selected action
    if (result == 'set_top') {
      _editItem();
    } else if (result == 'delete') {
      _deleteItem();
    }
  }

  void _editItem() {
    print("Edit item ");
  }

  void _deleteItem() {
    Get.dialog(
      barrierDismissible: false,
      AlertDialog(
        title: const Text(
          '删除聊天记录',
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
        ),
        contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
        actionsPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
        content: const Text('删除后将清除本会话的聊天记录', style: TextStyle(fontSize: 14)),
        actions: [
          TextButton(
            onPressed: () {
              Get.back(); // Close the dialog
            },
            child: const Text('取消', style: TextStyle(fontSize: 16, color: Colors.grey)),
          ),
          TextButton(
            onPressed: () {
              deleteChat(pipeInfo.id);
              Get.back();
            },
            child: const Text('确定', style: TextStyle(fontSize: 16, color: Colors.red)),
          ),
        ],
      ),
    );
  }

  String? _extractTextFromHtml(String htmlString) {
    // final document = parse(htmlString);
    // String? parsedString = parse(document.body?.text).documentElement?.text;
    // return parsedString;

    final document = parse(htmlString);
    return document.body?.text;
  }

  @override
  Widget build(BuildContext context) {
    final time = timeAgoSinceDate(pipeInfo.updatedTime);
    final message = _getLatestMsg();

    String? content = message;
    if (isMarkdown(message)) {
      content = markdown.markdownToHtml(message);
    }
    content = _extractTextFromHtml(content);

    return GestureDetector(
      onLongPressStart: (details) => _showContextMenu(context, details.globalPosition),
      onTap: () {
        var pipeId = pipeInfo.id ?? "";
        Get.toNamed(Routes.CHAT, arguments: {"pipeId": pipeId});
      },
      child: Container(
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                DecoratedBox(
                  decoration: BoxDecoration(
                    color: Colors.grey[200],
                    borderRadius: BorderRadius.circular(5.0),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 0),
                    child: Text(
                      pipeInfo.name,
                      style: const TextStyle(fontSize: 14.0, color: Colors.black87, fontWeight: FontWeight.w600),
                    ),
                  ),
                ),
                const Spacer(),
                Text(time, style: TextStyle(fontSize: 11.0, color: Colors.grey[400])),
              ],
            ),
            const SizedBox(height: 5),
            Text(
              content ?? "",
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
              style: const TextStyle(fontSize: 13.0, color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }
}
